# default pygame main file
import pygame, sys, random

from twisted.spread import pb
from twisted.internet import reactor
from twisted.cred import credentials
from pygame.locals import *

from mouse import *
from scrollWin import *

class game_c(pb.Referenceable):
	def __init__(self, programTitle):
		""" DISPLAY INITIALISATION """
		self.windowSize=(800,600)
		self.window = pygame.display.set_mode(self.windowSize, HWSURFACE|DOUBLEBUF)
		pygame.display.set_caption(programTitle)
		self.screen = pygame.display.get_surface()

		""" GAME VARIABLES """
		self.endGame = False
		self.perspective = None
		self.factory = None
		self.mouse = mouse_c()
		self.username = str(random.random())
		self.gameList = networkGameList_c((5,5), (700,300))
		
		""" LOAD MEDIA """
		#Load your media here
		
		""" START YOUR ENGINE """
		self.connect()
		#self.startWithoutConnect()
	
	def remote_print(self, message):
		print message

	def connect(self):
		self.factory = pb.PBClientFactory()
		reactor.connectTCP("localhost", 8800, self.factory, timeout=5)
		dfr = self.factory.getRootObject()

		dfr.addCallback(self.login)
		dfr.addErrback(self.connectFailed)
		reactor.run()

	def login(self, thing):
		def1 = self.factory.login(credentials.UsernamePassword("anon", "anon"), client=self)
		#def1 = self.factory.login(credentials.Anonymous, client=self)
		def1.addCallback(self.connected)
		def1.addErrback(self.loginFailed)

	def startWithoutConnect(self):
		reactor.callLater(0.03, self.main)
		reactor.run()
		
	def connectFailed(self, error):
		print "Connection Failed", error
		reactor.stop()
		
	def loginFailed(self, error):
		print "Login Failed"
		reactor.stop()

	#set up the perspective Var which is a pointer to the user object on the server
	def connected(self, perspective):
		self.perspective = perspective
		
		#start looping the main func
		self.main()
		self.checkForGames()
	
	#will this need to change if we're not connected?
	def shutDown(self):
		reactor.stop()

	def checkEvents(self, events):
		for event in events:
			if event.type == QUIT:
				self.endGame=True
			elif event.type == MOUSEMOTION:
				self.mouse.setPos((event.pos[0], event.pos[1]))
			elif event.type == MOUSEBUTTONDOWN:
				self.mouse.setButton(event.button-1,1)
			elif event.type == MOUSEBUTTONUP:
				self.mouse.setButton(event.button-1,0)

	def processInput(self):
		if self.mouse.buttons[0]:
			self.gameList.click(self.mouse.pos)

	#the draw function, all your draw code goes before the flip
	def draw(self):
		self.screen.fill((0,0,0,255))
		if self.mouse.getButton(0):
			self.perspective.callRemote("mouseClick", self.mouse.getPos(), 0)
		pygame.draw.circle(self.screen, (200, 200, 200, 255), self.mouse.getPos(), 24)
		#i'm not sure i'm happy with this one, should just ask it to draw itself or something:
		self.screen.blit(self.gameList.draw(), self.gameList.pos)
		pygame.display.flip()
	
	def checkForGames(self):
		d = self.perspective.callRemote("getGames")
		d.addCallback(self.gotGames)
		reactor.callLater(3, self.checkForGames)

	def gotGames(self, games):
		print "got the gamelist"

		self.gameList.clearItems()
		for game in games:
			self.gameList.addItem(game)
	
	#main func, might want to split up the timings a bit, for eg, check events less often than draw or something?
	def main(self):
		self.checkEvents(pygame.event.get())
		self.processInput()
		self.draw()
	
		#if endGame has been set, call the shutdown function
		if self.endGame==True:
			self.shutDown()

		#come back here at a rate of approx 30fps
		reactor.callLater(0.03, self.main)

if __name__=="__main__":
	pygame.init()
	pygame.mixer.init(7092)
	pygame.mouse.set_visible(0)
	game = game_c('Game Browser')